package pay.serviceImpl.dao.base.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

import pay.common.HqlFilter;
import pay.serviceImpl.dao.base.IBaseRepository;

@NoRepositoryBean
public class BaseRepositoryImpl<T, ID extends Serializable> extends
		SimpleJpaRepository<T, ID> implements IBaseRepository<T, ID> {
	private final EntityManager entityManager;

	// Class<T> clazz;

	public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
		super(domainClass, em);

		entityManager = em;
		// clazz = (Class<T>) ((ParameterizedType) this.getClass()
		// .getGenericSuperclass()).getActualTypeArguments()[0];
	}

	/**
	 * 获得当前事物的session
	 * 
	 * @return org.hibernate.Session
	 */
	public BaseRepositoryImpl(
			final JpaEntityInformation<T, ?> entityInformation,
			final EntityManager entityManager) {
		super(entityInformation, entityManager);
		this.entityManager = entityManager;
	}

	public String sharedCustomMethod() {
		return "hello sharedCustomMethod";
		// implementation goes here
	}

	// public T getT() throws InstantiationException, IllegalAccessException {
	// Type sType = getClass().getGenericSuperclass();
	// Type[] generics = ((ParameterizedType) sType).getActualTypeArguments();
	// Class<T> mTClass = (Class<T>) (generics[0]);
	// return mTClass.newInstance();
	// }

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getByHql(String hql, Map<String, Object> params) {
		Session session = entityManager.unwrap(org.hibernate.Session.class);
		Query q = session.createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				q.setParameter(key, params.get(key));
			}
		}
		List<T> l = q.list();
		if (l != null && l.size() > 0) {
			return l;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findByFilter(HqlFilter hqlFilter, String className) {
		// String className = ((Class<T>) ((ParameterizedType) getClass()
		// .getGenericSuperclass()).getActualTypeArguments()[0]).getName();
		// //String className = "SysUser";
		String hql = "select distinct t from " + className + " t";

		return getByHql(hql + hqlFilter.getWhereAndOrderHql(),
				hqlFilter.getParams());
	}
}
